package com.bear.fastrepair.mvvm.ui.login

import android.annotation.SuppressLint
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.annotation.StringRes
import androidx.cardview.widget.CardView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.bear.fastrepair.*
import com.bear.fastrepair.base.BaseFragment
import com.bear.fastrepair.databinding.FragmentLoginBinding
import com.bear.fastrepair.mvvm.ui.MainViewModel
import com.bear.fastrepair.mvvm.ui.MainViewModelFactory
import com.bear.fastrepair.utils.ERROR_CODE_PASSWORD
import com.bear.fastrepair.utils.ERROR_CODE_VERIFICATION_CODE
import com.bear.fastrepair.utils.TYPE_EMPLOYEE
import com.bear.fastrepair.utils.TYPE_MANAGER
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomnavigation.BottomNavigationView

class LoginFragment : BaseFragment<FragmentLoginBinding>() {

    private lateinit var loginViewModel: LoginViewModel
    private lateinit var viewModel: MainViewModel
    private lateinit var navController: NavController

    @SuppressLint("UseCompatLoadingForDrawables", "ResourceAsColor")
    override fun init() {
        val bottomCardView =
            requireActivity().findViewById<CardView>(R.id.bottom_card_view)
        navController = findNavController()
        bottomCardView.visibility = View.GONE
        loginViewModel = ViewModelProvider(this, LoginViewModelFactory())
            .get(LoginViewModel::class.java)
        viewModel =
            ViewModelProvider(
                requireActivity(),
                MainViewModelFactory()
            ).get(MainViewModel::class.java)
//        loginViewModel.getVerificationCode()
        // 获取已登录用户的信息
        loginViewModel.getLoggedInUser()

        val usernameEditText = binding.username
        val passwordEditText = binding.password
        val loginButton = binding.login
        val loadingProgressBar = binding.loading
//        val employeeRadioButton = binding.rbEmployee
//        val managerRadioButton = binding.rbAdmin

        loginViewModel.loginResult.observe(viewLifecycleOwner,
            Observer { loginResult ->
                loadingProgressBar.visibility = View.GONE
                loginResult ?: kotlin.run {
                    showLoginFailed(-1)
                    return@Observer
                }
                loginResult.error?.let {
                    showLoginFailed(it)
                }
                loginResult.success?.let {
                    updateUiWithUser(it)
                    loginViewModel.getPersonalInfo()
                    when (it.loginType) {
                        TYPE_MANAGER -> {
                            viewModel.loginStatus()
                            val bottomNavigationView =
                                requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navi)
                            bottomCardView.visibility = View.VISIBLE
                            bottomNavigationView.visibility = View.VISIBLE
                            bottomNavigationView.setupWithNavController(navController)
                            navController.navigate(R.id.managerOrderFragment)
                        }
                        TYPE_EMPLOYEE -> {
                            val bottomNavigationView =
                                requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navi_employee)
                            bottomCardView.visibility = View.VISIBLE
                            bottomNavigationView.visibility = View.VISIBLE
                            bottomNavigationView.setupWithNavController(navController)
                            navController.popBackStack()
                            navController.navigate(R.id.employeeOrderFragment)
                        }
                        else -> {
                            Log.i(javaClass.simpleName, "init: no such user type")
                        }
                    }
                }
            })

        loginViewModel.personalInfo.observe(viewLifecycleOwner) {
            if (it.code == 0 && !loginViewModel.webSocketStart) {
                loginViewModel.webSocketStart = true
                (requireActivity() as MainActivity).startWebSocket(it.data.id)
            }
        }

        loginViewModel.loginLoggedInUser.observe(viewLifecycleOwner) {
            // 如果用户已登录过，默认填充已登录用户的用户名以及密码
            it?.let { loggedInUser ->
                usernameEditText.setText(loggedInUser.userName)
                passwordEditText.setText(loggedInUser.password)
//                when (loggedInUser.type) {
//                    TYPE_MANAGER -> {
//                        managerRadioButton.isChecked = true
//                    }
//                    TYPE_EMPLOYEE -> {
//                        employeeRadioButton.isChecked = true
//                    }
//                    else -> {
//                        Log.i(javaClass.simpleName, "init: no such user type")
//                    }
//                }
            }
            loginViewModel.loginFormState.observe(viewLifecycleOwner,
                Observer { loginFormState ->
                    if (loginFormState == null) {
                        return@Observer
                    }
                    loginButton.isEnabled = loginFormState.isDataValid
                    loginFormState.usernameError?.let { error ->
                        usernameEditText.error = getString(error)
                    }
                    loginFormState.passwordError?.let { error ->
                        passwordEditText.error = getString(error)
                    }
                })
        }

//        loginViewModel.loginVerificationCode.observe(viewLifecycleOwner,
//            Observer { verificationBmp ->
//                if (verificationBmp == null) {
//                    ToastUtils.showLong("获取验证码失败，请检查网络连接！！！")
//                    return@Observer
//                }
//                Glide.with(this).load(verificationBmp).into(verificationCodeImageView)
//            })

        val afterTextChangedListener = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                // ignore
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                // ignore
            }

            override fun afterTextChanged(s: Editable) {
                loginViewModel.loginDataChanged(
                    usernameEditText.text.toString(),
                    passwordEditText.text.toString()
                )
            }
        }
        usernameEditText.addTextChangedListener(afterTextChangedListener)
        passwordEditText.addTextChangedListener(afterTextChangedListener)
        passwordEditText.setOnEditorActionListener { _, actionId, _ ->
//            val loginType = if (employeeRadioButton.isChecked) TYPE_EMPLOYEE else TYPE_MANAGER
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                loginViewModel.login(
                    usernameEditText.text.toString(),
                    passwordEditText.text.toString(),
                    1
                )
            }
            false
        }

        loginButton.setOnClickListener {
//            val loginType = if (employeeRadioButton.isChecked) 1 else 0
            loadingProgressBar.visibility = View.VISIBLE
            loginViewModel.login(
                usernameEditText.text.toString(),
                passwordEditText.text.toString(),
                1,
            )
        }

        binding.cbShowPassword.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) passwordEditText.inputType =
                InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
            else passwordEditText.inputType =
                InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        }

//        verificationCodeImageView.setOnClickListener {
//            loginViewModel.getVerificationCode()
//        }
    }

    private fun updateUiWithUser(model: ResponseInfoView) {
        val welcome = getString(R.string.welcome) + model.displayName
        ToastUtils.showLong(welcome)
    }

    private fun showLoginFailed(@StringRes errorString: Int) {
//        loginViewModel.getVerificationCode()
        when (errorString) {
            ERROR_CODE_PASSWORD -> ToastUtils.showLong("账号或密码不正确，请重新输入")
            ERROR_CODE_VERIFICATION_CODE -> ToastUtils.showLong("验证码不正确，请重新输入")
        }
    }

    override val title: String
        get() = "登录"
}